<template>
  <div>
    <div class="page-card m-top">
      <el-table
        stripe
        border
        v-loading="loading"
        :data="computedTotalRow"
        row-key="schoolId"
        >
        <el-table-column
          label="学校名称"
          align="center"
          prop="schoolName"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="物理" align="center" v-if="type===0">
          <el-table-column
          label="人数"
          align="center"
          prop="preportedNumber"
          :show-overflow-tooltip="true"
        />
          <el-table-column
          v-for="item in headerTitle"
            :key="item.prop"
            :label="item.label"
            align="center"
            width="100"
            :prop="'P_'+item.prop"
            :show-overflow-tooltip="true"
          >
        <template slot-scope="scope">
          <el-input v-if="!item.prop.endsWith('_S')" 
          @input="handleInput($event, scope.row, 'P_'+item.prop,'preportedNumber')"
          v-model="scope.row['P_'+item.prop]" placeholder="请输入" :disabled="scope.$index !== 0" size="mini">
          </el-input>
          <span v-else>{{isNaN(Number(scope.row['P_'+item.prop]))?0:(Number(scope.row['P_'+item.prop]))+'%'}}</span>

          <!-- {{scope.row['P_'+item.prop]}} -->

        </template>
        </el-table-column>
         
        </el-table-column>
        <el-table-column label="历史" align="center" v-if="type===0">
          <el-table-column
          label="人数"
          align="center"
          prop="hreportedNumber"
          :show-overflow-tooltip="true"
        />
            <el-table-column
          v-for="item in headerTitle"
            :key="item.prop"
            :label="item.label"
            align="center"
            width="100"
            :prop="'H_'+item.prop"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="scope">
            <el-input v-if="!item.prop.endsWith('_S')" 
          @input="handleInput($event, scope.row, 'H_'+item.prop,'hreportedNumber')"

              v-model="scope.row['H_'+item.prop]" placeholder="请输入" :disabled="scope.$index !== 0" size="mini">
            </el-input>
          <span v-else>{{isNaN(Number(scope.row['H_'+item.prop]))?0:(Number(scope.row['H_'+item.prop]))+'%'}}</span>

          </template>
          </el-table-column>
         
        </el-table-column>
        <template v-if="type===1">
           <el-table-column
          label="人数"
          align="center"
          prop="reportedNumber"
          :show-overflow-tooltip="true"
        />
           <el-table-column
          v-for="item in headerTitle"
            :key="item.prop"
            :label="item.label"
            align="center"
            width="180"
            :prop="item.prop"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="scope">
               <el-input v-if="!item.prop.endsWith('_S')" 
          @input="handleInput($event, scope.row, 'N_'+item.prop,'reportedNumber')"

              v-model="scope.row['N_'+item.prop]" placeholder="请输入" :disabled="scope.$index !== 0" size="mini">
            </el-input>
          <span v-else>{{isNaN(Number(scope.row['N_'+item.prop]))?0:(Number(scope.row['N_'+item.prop]))+'%'}}</span>
          </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" align="center" fixed="right" width="150">

          <template slot-scope="scope" v-if="scope.$index == 0">
            <!-- {{ Boolean(examData) }}{{ scope.row.disabled }} -->
            <el-popconfirm
              :title="'确定编辑'+scope.row.schoolName+'的分数线吗？'"
              @confirm="saveSchool(scope.row)"      
               v-if="examData"
            >
            <el-link  type="primary" v-if="examData " slot="reference">编辑</el-link>
            </el-popconfirm>
            <el-link @click="saveSchool(scope.row)" type="primary" v-if="!examData ">保存</el-link>
            <!-- <el-link @click="cancelEdit(scope.row)" type="primary" v-if="!examData ">取消</el-link> -->
            <el-popconfirm
              :title="'确定清空'+scope.row.schoolName+'的分数线吗？'"
              @confirm="saveSchool(scope.row,1)"      
               v-if="examData "
            >
              <el-link slot="reference" type="danger">清空</el-link>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { launchInfoList, launchInfoEdit, launchInfoClear } from '@/api/xmgl/cjgl';
import { debounce } from 'lodash';

export default {
  props: {
    xmxx: null,
  },
  data() {
    return {
      type:'',
      loading: false,
      tableData: [],// 改造后展示的表格数据
      rawData: [],// 原始数据，用于编辑、清空
      admissionLine:[],// 录取线
      admissionLineAll:[],// 联考-录取线
      fields:[],// 表格字段
      headerTitle:[],// 表头
      totalRow:{},// 合计行
      computedTotalRow:[],// 合计行-计算
      examData:null// 联考-数据
    };
  },
  computed:{
  },
  watch:{
    tableData:{
      handler(newVal,oldVal){
        
       this.processData();

      },
      deep:true
    }
  },

  created() {
    this.getList();
  },
  methods: {
       processData() {
      try {
        // 提取字段名
        this.fields = Object.keys(this.tableData[0]);

        
        // 根据配置确定数字字段
        let numericFields = [];
        
        // if (this.config.autoDetect) {
        //   // 自动检测数字字段
        //   numericFields = this.fields.filter(field => {
        //     const value = data[0][field];
        //     return typeof value === 'number' && !isNaN(value);
        //   });
        // } else {
        //   // 使用用户指定的数字字段
        //   numericFields = this.config.numericFields;
        // }
        
        // // 添加自定义字段
        // if (this.config.customFields.length > 0) {
        //   numericFields = [...new Set([...numericFields, ...this.config.customFields])];
        // }
        // 处理每个字段
        let inputFields = this.admissionLine.map(r=>r.name);
this.$nextTick(()=>{
      this.$set(this.totalRow,'disabled', true);
        this.fields.forEach(field => {
          if(field === 'schoolName'){
              this.totalRow[field] = '联考';
          }
          if(field === 'preportedNumber' && !this.examData){
            // 物理人数
            this.totalRow[field] = this.tableData.reduce((sum, item) => {
              const value = item[field];
              return sum + (typeof value === 'number' ? value : 0);
            }, 0);
          }
          if(field === 'hreportedNumber' && !this.examData){
            // 历史人数
            this.totalRow[field] = this.tableData.reduce((sum, item) => {
              const value = item[field];
              return sum + (typeof value === 'number' ? value : 0);
            }, 0);
          }
          if(field === 'reportedNumber' && !this.examData){
            // 人数
            this.totalRow[field] = this.tableData.reduce((sum, item) => {
              const value = item[field];
              return sum + (typeof value === 'number' ? value : 0);
            }, 0);
          }
          inputFields.forEach(item=>{
            if (field.split('_S')[0] === 'P_'+item) {
                // 物理录取线
                // this.totalRow['P_'+item] = this.tableData.reduce((sum, item1) => {
                //   const value = item1['P_'+item];
                //   return sum + (typeof value === 'number' ? value : 0);
                // }, 0);
                if(!this.examData){
                this.$set(this.totalRow,'P_'+item, this.computedTotalRow.reduce((sum, item1) => {
                  const value = item1['P_'+item];
                  return sum + (typeof value === 'number' ? value : 0);
                }, 0));
                }

                // 物理占比
                // this.totalRow[field] = (this.totalRow['P_'+item] / this.totalRow['preportedNumber'] * 100).toFixed(2);
                this.$set(this.totalRow,'P_'+item+'_S',  (this.totalRow['P_'+item] / this.totalRow['preportedNumber'] * 100).toFixed(2));
            }
            if (field.split('_S')[0] === 'H_'+item ) {
              // 历史录取线
              // this.totalRow['H_'+item] = this.tableData.reduce((sum, item1) => {
              //   const value = item1['H_'+item];
              //   return sum + (typeof value === 'number' ? value : 0);
              // }, 0);
                if(!this.examData){
                this.$set(this.totalRow,'H_'+item, this.computedTotalRow.reduce((sum, item1) => {
                  const value = item1['H_'+item];
                  return sum + (typeof value === 'number' ? value : 0);
                }, 0));
                }

                // this.totalRow[field] = (this.totalRow['H_'+item] / this.totalRow['hreportedNumber'] * 100).toFixed(2);
                this.$set(this.totalRow,'H_'+item+'_S', (this.totalRow['H_'+item] / this.totalRow['hreportedNumber'] * 100).toFixed(2));
            }
            if (field.split('N_')[1] === item) {
              // 不区分录取线
              this.$set(this.totalRow,item, this.tableData.reduce((sum, item1) => {
                const value = item1['N_'+item];
                return sum + (typeof value === 'number' ? value : 0);
              }, 0));
                this.$set(this.totalRow,field, (this.totalRow['N_'+item] / this.totalRow['reportedNumber'] * 100).toFixed(2));
            }
          })
        });
        if (this.examData) {
        this.computedTotalRow = this.tableData;
        }else{
          this.computedTotalRow = [].concat( [this.totalRow],this.tableData);
        }
        // this.computedTotalRow = [].concat( [this.totalRow],this.tableData);
})
      } catch (error) {
        // console.error('数据格式错误:', error);
        this.processedData = [];
        this.fields = [];
      }
    },
    handleInput:debounce(function(e, row, prop, reportedNumber) {
      let Drow = this.computedTotalRow.filter(item => item.schoolId === row.schoolId)[0]
      
      if(isNaN(Number(e))){
        Drow[prop] = 0
      }else{
        if (Number(e)>Drow[reportedNumber]) {
          // console.log(Drow[reportedNumber],'Drow[reportedNumber]');
          
          // Drow[prop] = Drow[reportedNumber]
          e = Drow[reportedNumber]
          this.$message({
            message: `${prop}不能大于人数`,
            type: 'error',
          })
        }
        this.$nextTick(() => {
          Drow[prop] = Number(e)
          Drow[prop+"_S"] = (Number(e)/Drow[reportedNumber]*100).toFixed(2);
        })

      }
      this.processData()
      this.$forceUpdate()
    }),
    // 保存编辑
    saveSchool(row,type) {
         let list = []
      let exam = this.computedTotalRow[0]
      if (type === 1) {
          this.admissionLineAll.forEach(item=>{
          if (this.type===0) {
            let obj = {
                  "id": item.id,
                  "examId": exam.examId,
                  "examPhysicsNum": exam.examPhysicsNum,//物理人数
                  "examHistoryNum": exam.examHistoryNum,//历史人数
                  "type": item.type,
                  // "fractionBarSign": 1,
                  "fractionBarName": item.name,
                  "reportYear": item.reportYear,
                  "physicsDirection": 0,//物理-线
                  "historicalDirection": 0,//历史-线
                  // "noDistinctionNumber": 0,
            }
            list.push(obj);
          }
          if (this.type===1) {
            let obj = {
                  "id": item.id,
                  "examId": exam.examId,
                  "noDistinctionNumber": exam.reportedNumber,//不区分总人数
                  // "examPhysicsNum": exam.examPhysicsNum,//物理人数
                  // "examHistoryNum": exam.examHistoryNum,//历史人数
                  "type": item.type,
                  // "fractionBarSign": 1,
                  "fractionBarName": item.name,
                  "reportYear": item.reportYear,
                  // "physicsDirection": 0,//物理-线
                  // "historicalDirection": 0,//历史-线
                  "noDirection": 0,//不区分上线人数
            }
            list.push(obj);
            // list.push(row.idBarList.filter(item1=>item1.name === item.name)[0].id+'_N_'+row[item.name]);
          }
        })
        launchInfoEdit(list).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '清空成功',
            type: 'success',
          })
          this.getList();
        }
      })
      return false
      }
   
      if (this.examData) {
        // 如果存在根据自己的admissionLineAll 来判断是物理线还是历史线
         this.admissionLineAll.forEach(item=>{
          if (this.type===0) {
            let obj = {
                  "id": item.id,
                  "examId": exam.examId,
                  "examPhysicsNum": exam.preportedNumber,//物理人数
                  "examHistoryNum":exam.hreportedNumber,//历史人数
                  "type": item.type,
                  // "fractionBarSign": 1,
                  "fractionBarName": item.name,
                  "reportYear": item.reportYear,
                  "physicsDirection": exam['P_'+item.name],//物理-线
                  "historicalDirection": exam['H_'+item.name],//历史-线
                  // "noDistinctionNumber": 0,
            }
            list.push(obj);
          }
          if (this.type===1) {
             let obj = {
                  "id": item.id,
                  "examId": exam.examId,
                  "noDistinctionNumber": exam.reportedNumber,//不区分总人数
                  // "examPhysicsNum": exam.examPhysicsNum,//物理人数
                  // "examHistoryNum": exam.examHistoryNum,//历史人数
                  "type": item.type,
                  // "fractionBarSign": 1,
                  "fractionBarName": item.name,
                  "reportYear": item.reportYear,
                  // "physicsDirection": 0,//物理-线
                  // "historicalDirection": 0,//历史-线
                  "noDirection": exam['N_'+item.name],//不区分上线人数
            }
            list.push(obj);
            // list.push(row.idBarList.filter(item1=>item1.name === item.name)[0].id+'_N_'+row[item.name]);
          }
        })
      }else{
        // 没有首条数据
        this.admissionLine.forEach(item=>{
          if (this.type===0) {
            let obj = {
                  "examId": this.xmxx.id,
                  "examPhysicsNum": exam.preportedNumber,//物理人数
                  "examHistoryNum":exam.hreportedNumber,//历史人数
                  "type": this.type,
                  // "fractionBarSign": 1,
                  "fractionBarName": item.name,
                  "reportYear": item.reportYear,
                  "physicsDirection": exam['P_'+item.name],//物理-线
                  "historicalDirection": exam['H_'+item.name],//历史-线
                  // "noDistinctionNumber": 0,
            }
            list.push(obj);
          }
          if (this.type===1) {
             let obj = {
                  "examId": this.xmxx.id,
                  "noDistinctionNumber": exam.reportedNumber,//不区分总人数
                  // "examPhysicsNum": exam.preportedNumber,//物理人数
                  // "examHistoryNum":exam.hreportedNumber,//历史人数
                  "type": this.type,
                  // "fractionBarSign": 1,
                  "fractionBarName": item.name,
                  "reportYear": item.reportYear,
                  // "physicsDirection": exam['P_'+item.name],//物理-线
                  // "historicalDirection": exam['H_'+item.name],//历史-线
                  "noDirection": exam['N_'+item.name],//不区分上线人数
            }
            list.push(obj);
            // list.push(row.idBarList.filter(item1=>item1.name === item.name)[0].id+'_N_'+row[item.name]);
          }
        })
      }
      launchInfoEdit(list).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '保存成功',
            type: 'success',
          })
          this.getList();
        }
      })
    },
    // 取消编辑
    cancelEdit(row) {
      row.disabled = true;
      // 取消编辑时，将数据回滚到原始数据
      let backup = JSON.parse(JSON.stringify(this.rawData.filter(item => item.schoolId === row.schoolId)[0]));
      Object.assign(row, backup);

    },
    // 清空成绩
    clearScore(row) {
      let list = []
      this.admissionLine.forEach(item=>{
        if (this.type===0) {
          list.push(row.idBarList.filter(item1=>item1.name === item.name)[0].id+'_P_0');
          list.push(row.idBarList.filter(item1=>item1.name === item.name)[0].id+'_H_0');
        }
        if (this.type===1) {
          list.push(row.idBarList.filter(item1=>item1.name === item.name)[0].id+'_N_0');
        }
      })
      launchInfoEdit(list).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '清空成功',
            type: 'success',
          })
          this.getList();
        }
      })
    },

    getList() {
      this.loading = true;
      launchInfoList({examId: this.xmxx.id}).then(res => {
        if (res.code === 200) {
          this.type = Number(res.data.type);// 0:文理，1：不区分
          this.admissionLine = res.data.scoreName;// 录取线
          this.admissionLineAll = res.data.onlineAdminDetail?.idBarList||[];// 录取线
          this.examData = res.data.onlineAdminDetail
          let list = []
          let headerTitle =[]
          const allList = [].concat(res.data.onlineAdminDetail?[res.data.onlineAdminDetail]:[],res.data.onlineAdminDetails)
          res.data.scoreName.forEach(item => {
               headerTitle.push({
                label: item.name,
                prop: item.name,
                key: item.name,
              })
               headerTitle.push({
                label: '占比',
                prop: item.name+'_S',
                key: item.name+'_S',
              })
            })
          if (this.type===0) {
            allList.forEach(item => {
              let obj = {
                ...item,
                id: item.id,
                schoolId: item.schoolId,
                schoolName: item.schoolName,
                disabled:true,
                ...item.scoreList[0],
                ...item.scorePreList[0],
              }
              list.push(obj);
            })
            // let all = {}
            // list.forEach(item => {
            //   item.P_S = item.P/Number(item.preportedNumber)
            //   item.H_S = item.H/Number(item.hreportedNumber)
            // })

            this.tableData = list;
          }
          if (this.type===1) {
            allList.forEach(item => {
              let obj = {
                ...item,
                id: item.id,
                schoolId: item.schoolId,
                schoolName: item.schoolName,
                disabled:true,
                 ...item.scoreList[0],
                ...item.scorePreList[0],
              }
              list.push(obj);
            })
            this.tableData = list;
          }
          this.rawData = JSON.parse(JSON.stringify(this.tableData));// 原始数据，用于编辑、清空
           this.processData()
            this.headerTitle = headerTitle
        }
      }).finally(() => {
        this.loading = false;
      });
    },
     getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '联考';
            return;
          }
           const prop = column.property;
          if (prop.endsWith('_S')) {
            switch (prop.split('_')[0]) {
              case 'P':
                // 区分物理成绩和占比
                const valuesP = data.map(item => Number(prop.split('_S')[0]) || 0);
                const valuesNum = data.map(item => Number(item.preportedNumber) || 0);
                sums[index] = valuesP/valuesNum;
                break;
              case "H":
                // 区分历史成绩和占比
                const valuesH = data.map(item => Number(prop.split('_S')[0]) || 0);
                const valuesNumH = data.map(item => Number(item.hreportedNumber) || 0);
                sums[index] = valuesH/valuesNumH;
              default:
                break;
            }
          }
          // const values = data.map(item => Number(item[column.property]));
          // if (!values.every(value => isNaN(value))) {
          //   sums[index] = values.reduce((prev, curr) => {
          //     const value = Number(curr);
          //     if (!isNaN(value)) {
          //       return prev + curr;
          //     } else {
          //       return prev;
          //     }
          //   }, 0);
          //   sums[index] += ' 元';
          // } else {
          //   sums[index] = 'N/A';
          // }
        });

        return sums;
      }
  },
};
</script>

<style scoped>
>>>.el-input.is-disabled .el-input__inner {

    background: #fff;
    color: #858585;
}
</style>